import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', redirect: '/Manage/Home' },
    {
      path: '/login',
      name: 'login',
      component: () => import('../components/User/Login.vue'),
    },
    {
      path: '/Manage',
      name: 'manage',
      component: Home,
      children: [
        {
          path: '/Manage/Home',
          name: 'home',
          component: () => import('@/components/Home/index.vue'),
        },
        {
          path: '/Manage/Community',
          name: 'community',
          component: () => import('@/components/Community/index.vue'),
        },

        {
          path: '/Manage/userList',
          name: 'user',
          component: () => import('@/components/User/User.vue'),
        },

        {
          path: '/Manage/Forum',
          name: 'forum',
          component: () => import('@/components/News/Forum.vue'),
        },
        {
          path: '/Manage/Notice',
          name: 'notice',
          component: () => import('@/components/News/Notice.vue'),
        },
        {
          path: '/Manage/Drugs',
          name: 'drugs',
          component: () => import('@/components/Drugs/index.vue'),
        },
        {
          path: '/Manage/DrugLibrary',
          name: 'drugLibrary',
          component: () => import('@/components/Drugs/drugLibrary.vue'),
        },
        {
          path: '/Manage/Reservation',
          name: 'reservation',
          component: () => import('@/components/Service/Reservation.vue'),
        },
        {
          path: '/Manage/Consultation',
          name: 'consultation',
          component: () => import('@/components/Service/Consultation.vue'),
        },
        {
          path: '/Manage/Scheduling',
          name: 'scheduling',
          component: () => import('@/components/User/Scheduling.vue'),
        },
      ],
    },
  ],
  scrollBehavior(to, from, savedPosition) {
    document.body.scrollTop = 0
    document.documentElement.scrollTop = 0
    // 始终滚动到顶部
    return { top: 0 }
  },
})

router.beforeEach((to, from, next) => {
  const isLogin = localStorage.getItem('authorityToken') ? true : false
  // 如果当前访问的是登录页面或者注册页面可以让它进入
  if (to.path == '/login') {
    next()
  } else {
    // 如果isLogin为true表示已经登录了;就让它正常进入就可以 ,如果没登录就让他进入登录页面
    if (isLogin) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
